package com.thinkingcoder.tcdfs.syncer;

import java.io.File;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.MultipartBodyBuilder;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import com.thinkingcoder.tcdfs.constant.CustomHeaderConstants;

/**
 * sync file to backup server.
 */
@Component
public class HttpSyncer {

    public String sync(File file, String url, String originalFilename) {

        RestTemplate restTemplate = new RestTemplate();

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        headers.add(CustomHeaderConstants.FileName.X_FILENAME,
            URLEncoder.encode(file.getName(), StandardCharsets.UTF_8));
        headers.add(CustomHeaderConstants.FileName.X_ORIGINAL_FILENAME,
            URLEncoder.encode(originalFilename, StandardCharsets.UTF_8));

        MultipartBodyBuilder builder = new MultipartBodyBuilder();
        builder.part("file", new FileSystemResource(file));

        HttpEntity<MultiValueMap<String, HttpEntity<?>>> httpEntity = new HttpEntity<>(builder.build(), headers);

        ResponseEntity<String> stringResponseEntity = restTemplate.postForEntity(url, httpEntity, String.class);
        String result = stringResponseEntity.getBody();
        System.out.println("sync result = " + result);
        return result;
    }
}
